package com.flyduck.vueshop.product.h5.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.vueshop.common.core.exception.BusinessException;
import com.flyduck.vueshop.common.core.utils.BeanUtils;
import com.flyduck.vueshop.common.core.utils.StringUtils;
import com.flyduck.vueshop.common.mybatis.utils.PageUtils;
import com.flyduck.vueshop.common.sotoken.utils.StpUserUtil;
import com.flyduck.vueshop.common.upload.manager.AppUploadManager;
import com.flyduck.vueshop.order.constant.OrderConstant;
import com.flyduck.vueshop.order.feign.RemoteOrderFeignClient;
import com.flyduck.vueshop.order.feign.RemoteOrderItemFeignClient;
import com.flyduck.vueshop.order.vo.RemoteOrderItemRespVO;
import com.flyduck.vueshop.order.vo.RemoteOrderItemUpdateReqVO;
import com.flyduck.vueshop.order.vo.RemoteOrderRespVO;
import com.flyduck.vueshop.product.entity.AppComment;
import com.flyduck.vueshop.product.entity.AppProduct;
import com.flyduck.vueshop.product.h5.service.H5CommentService;
import com.flyduck.vueshop.product.h5.vo.H5CommentDetailsRespVO;
import com.flyduck.vueshop.product.h5.vo.H5CommentPostReqVO;
import com.flyduck.vueshop.product.h5.vo.H5CommentRespVO;
import com.flyduck.vueshop.product.mapper.AppCommentMapper;
import com.flyduck.vueshop.product.mapper.AppProductMapper;
import com.flyduck.vueshop.user.feign.RemoteUserFeignClient;
import com.flyduck.vueshop.user.vo.RemoteUserRespVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-23 21:38
 **/
@Service
public class H5CommentServiceImpl implements H5CommentService {

    @Resource
    private AppCommentMapper appCommentMapper;
    @Resource
    private AppUploadManager appUploadManager;
    @Resource
    private AppProductMapper appProductMapper;
    @Resource
    private RemoteOrderFeignClient remoteOrderFeignClient;
    @Resource
    private RemoteOrderItemFeignClient remoteOrderItemFeignClient;
    @Resource
    private RemoteUserFeignClient remoteUserFeignClient;

    @Override
    public Page<H5CommentRespVO> getCommentPageByProductId(Page page, Long productId) {
        Page<AppComment> appCommentPage = appCommentMapper.selectPage(page,
                new LambdaQueryWrapper<AppComment>()
                        .eq(AppComment::getProductId,productId)
                        .orderByDesc(AppComment::getCreated)
        );

        Page<H5CommentRespVO> h5CommentRespVOPage = PageUtils.convert(appCommentPage, H5CommentRespVO.class);
        for (H5CommentRespVO h5CommentRespVO : h5CommentRespVOPage.getRecords()) {
            RemoteUserRespVO remoteUserRespVO = remoteUserFeignClient.getUserById(h5CommentRespVO.getUserId()).getData();
            h5CommentRespVO.setUsername(remoteUserRespVO.getUsername());
            h5CommentRespVO.setUserAvatar(remoteUserRespVO.getAvatar());
        }
        return h5CommentRespVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long postComment(MultipartFile[] pics, H5CommentPostReqVO h5CommentPostReqVO) {
        Long userId = StpUserUtil.getLoginIdAsLong();
        //1、条件判断
        RemoteOrderItemRespVO remoteOrderItemRespVO = remoteOrderItemFeignClient.getOrderItemById(h5CommentPostReqVO.getOrderItemId()).getData();
        if(remoteOrderItemRespVO.getCommentId() != null){
            throw new BusinessException("请勿重复评论");
        }
        RemoteOrderRespVO remoteOrderRespVO = remoteOrderFeignClient.getOrderById(remoteOrderItemRespVO.getOrderId()).getData();
        if(remoteOrderRespVO == null){
            throw new BusinessException("订单不存在");
        }
        if (!userId.equals(remoteOrderRespVO.getUserId())) {
            throw new BusinessException("无权限操作该订单");
        }
        if (OrderConstant.OrderStatus.COMPLETED.getCode() != remoteOrderRespVO.getOrderStatus()) {
            throw new BusinessException("该订单无法评论");
        }

        //2、图片处理
        List<String> picUrls = new ArrayList<>();
        if(ArrayUtil.isNotEmpty(pics)){
            try {
                picUrls = appUploadManager.upload(pics, 0.5f, 0.2);
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException("图片上传失败");
            }
        }

        //3、保存评论
        AppComment appComment = new AppComment();
        appComment.setUserId(userId);
        appComment.setProductId(remoteOrderItemRespVO.getProductId());
        appComment.setOrderItemId(remoteOrderItemRespVO.getId());
        appComment.setOrderId(remoteOrderRespVO.getId());
        appComment.setContent(h5CommentPostReqVO.getContent());
        appComment.setScore(h5CommentPostReqVO.getScore());
        appComment.setImages(StringUtils.join(";", picUrls));
        appComment.setCreated(LocalDateTime.now());
        appCommentMapper.insert(appComment);

        //4、更新订单明细的评论id和评论时间
        RemoteOrderItemUpdateReqVO remoteOrderItemUpdateReqVO = new RemoteOrderItemUpdateReqVO();
        remoteOrderItemUpdateReqVO.setId(remoteOrderItemRespVO.getId());
        remoteOrderItemUpdateReqVO.setCommentId(appComment.getId());
        remoteOrderItemUpdateReqVO.setCommentTime(LocalDateTime.now());
        remoteOrderItemFeignClient.updateOrderItem(remoteOrderItemUpdateReqVO);

        //5、商品评论数量+1
        appProductMapper.update(
                new LambdaUpdateWrapper<AppProduct>()
                 .eq(AppProduct::getId,remoteOrderItemRespVO.getProductId())
                .setSql("comments = comments + 1")
        );

        return appComment.getId();

    }

    @Override
    public H5CommentDetailsRespVO getCommentDetailsById(Long id) {
        AppComment appComment = appCommentMapper.selectById(id);
        return BeanUtils.toBean(appComment, H5CommentDetailsRespVO.class);

    }
}
